<template>
  <div class="page-form">
    <div class="form-wrapper center">
      <h1>{{$route.meta.title}}</h1>
      <el-form size="small" inline label-width="auto" ref="form" :model="form" class="form">
        <div class="block">
          <div class="title-bar">
            <div class="title"><h2>委托及收货信息</h2><i class="required"></i></div>
            <div class="op">
              <el-button size="mini" type="primary" plain @click="openSettlementAdder">添加客户</el-button>
            </div>
          </div>
          <div class="content">
            <el-row :gutter="layout.colGutter">
              <el-col :span="layout.colSpan">
                <el-form-item label="委托联系电话" prop="linkmanPhone" :rules="[{required: true, message: '请选择'}]">
                  <ad-suggestion v-model="form.linkmanPhone" defaultProp="linkmanPhone" type="table"
                                 @select="selectLink" @clear="removeLink"
                                 :api="{method: getSuggestCompanyList, query: 'linkmanPhone', startQueryCount: 4}"
                                 :options="[{label: '委托联系电话', prop: 'linkmanPhone'},{label: '委托联系人', prop: 'linkmanName'},{label: '公司名称', prop: 'companyName'}]"/>
                </el-form-item>
              </el-col>
              <el-col :span="layout.colSpan">
                <el-form-item label="委托联系人" prop="linkmanName" :rules="[{required: true, message: '请选择'}]">
                  <ad-suggestion v-model="form.linkmanName" defaultProp="linkmanName" type="table" @select="selectLink"
                                 @clear="removeLink"
                                 :api="{method: getSuggestCompanyList, query: 'linkmanName'}"
                                 :options="[{label: '委托联系电话', prop: 'linkmanPhone'},{label: '委托联系人', prop: 'linkmanName'},{label: '公司名称', prop: 'companyName'}]"/>
                </el-form-item>
              </el-col>
              <el-col :span="layout.colSpan" v-if="showCompany">
                <el-form-item label="公司名称" prop="companyName" :rules="[{required: true, message: '请选择'}]">
                  <ad-suggestion v-model="form.companyName" defaultProp="companyName" type="table" @select="selectLink"
                                 @clear="removeLink"
                                 :api="{method: getSuggestCompanyList, query: 'companyName'}"
                                 :options="[{label: '委托联系电话', prop: 'linkmanPhone'},{label: '委托联系人', prop: 'linkmanName'},{label: '公司名称', prop: 'companyName'}]"/>
                </el-form-item>
              </el-col>
              <el-col :span="layout.colSpan" v-if="suggestedCustomerLineList.length > 0">
                <el-form-item label="线路信息" prop="customerLineId">
                  <ad-select v-model="form.customerLineId" :options="suggestedCustomerLineList"
                             :config="{optionKey: 'lineName', optionValue: 'id'}"
                             @select="selectSuggestedCustomerLine"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="layout.colGutter">
              <el-col :span="layout.colSpan">
                <el-form-item label="收货联系人" prop="consigneeName" :rules="[{required: true, message: '请输入'}]">
<!--                  <ad-suggestion v-model="form.consigneeName" defaultProp="linkmanId" type="table" @select="selectLinkConsignee"-->
<!--                                 @clear="removeConsignee"-->
<!--                                 reserveInput-->
<!--                                 :api="{method: getSuggestBargainList, query: 'linkmanId'}"-->
<!--                                 :options="[{label: '收货联系电话', prop: 'phone'},{label: '收货联系人', prop: 'name'}]"/>-->
<!--                  <el-input v-model="form.consigneeName" placeholder="请输入"/>-->
                  <el-select @change="selectNamePhone" v-model="form.consigneeName" filterable placeholder="请输入" :filter-method="dataFilterConsigneeName">
                    <el-option
                      v-for="item in options"
                      :key="item.id"
                      :label="item.name"
                      :value="item.name">
                      <span style="float: left">{{ item.name }}</span>
                      <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="layout.colSpan">
                <el-form-item label="收货联系电话" prop="consigneePhone" :rules="[{required: true, message: '请输入'}]">
<!--                  <ad-suggestion v-model="form.consigneePhone" defaultProp="phone" type="table" @select="selectLinkConsignee"-->
<!--                                 @clear="removeConsignee"-->
<!--                                 reserveInput-->
<!--                                 :api="{method: getSuggestBargainList, query: 'phone', startQueryCount: 4}"-->
<!--                                 :options="[{label: '收货联系电话', prop: 'phone'},{label: '收货联系人', prop: 'name'}]"/>-->
<!--                  <el-input-number v-model.number="form.consigneePhone" :controls="false" :min="0" :precision="0"-->
<!--                                   placeholder="请输入" class="tel"/>-->
                  <el-select @change="selectNamePhone" v-model="form.consigneePhone" filterable placeholder="请输入"  :filter-method="dataFilterConsigneePhone">
                    <el-option
                      v-for="item in options"
                      :key="item.id"
                      :label="item.phone"
                      :value="item.phone">
                      <span style="float: left">{{ item.name }}</span>
                      <span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </div>
        <div class="block">
          <div class="title-bar">
            <div class="title"><h2>路线及提送信息</h2><i class="required"></i></div>
          </div>
          <div class="content">
            <el-row :gutter="layout.colGutter">
              <el-col :span="layout.colSpan">
                <el-form-item label="出发地" prop="startCode" :rules="[{required: true, message: '请选择'}]">
                  <ad-city-select v-model="form.startCode" @select="selectCity"/>
                </el-form-item>
              </el-col>
              <el-col :span="layout.colSpan">
                <el-form-item label="提车方式" prop="pickType" :rules="[{required: true, message: '请选择'}]">
                  <ad-status-select v-model="form.pickType" :dict="dict.pickcar_type" @select="selectPickType"/>
                </el-form-item>
              </el-col>
              <el-col :span="layout.colSpan">
                <el-form-item label="提车联系人" prop="pickLinkmanName" v-if="form.pickType == 1 || form.pickType == 2"
                              :rules="[{required: true, message: '请选择'}]">
                  <el-input v-model="form.pickLinkmanName" placeholder="请输入"/>
                </el-form-item>
              </el-col>
              <el-col :span="layout.colSpan" v-if="form.pickType == 1 || form.pickType == 2">
                <el-form-item label="提车联系电话" prop="pickLinkmanPhone" :rules="[{required: true, message: '请输入'}]">
                  <el-input v-model="form.pickLinkmanPhone" placeholder="请输入"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="layout.colGutter">
              <template v-if="form.pickType && (form.pickType == 1 || form.pickType == 2 || form.pickType == 4)">
                <el-col :span="layout.colSpan" v-if="pickAreaData.length > 0">
                  <el-form-item label="提车地址" prop="pickAreaCode" :rules="[{required: true, message: '请选择'}]">
                    <ad-select placeholder="区" v-model="form.pickAreaCode" :options="pickAreaData"
                               :config="{optionKey: 'name', optionValue: 'code'}"/>
                  </el-form-item>
                </el-col>
                <el-col :span="layout.colSpan" :class="{pull: pickAreaData.length > 0}"
                        :style="pickAreaData.length > 0 ? 'padding-left: 0' : ''">
                  <el-form-item :label="pickAreaData.length == 0 ? '提车地址' : ''" prop="pickAddress"
                                :rules="[{required: true, message: '请输入'}]">
                    <el-input v-model="form.pickAddress" placeholder="请输入详细地址"/>
                  </el-form-item>
                </el-col>
              </template>
            </el-row>
            <div class="line" :style="`margin-bottom: ${layout.rowGutter}px`"></div>
            <el-row :gutter="layout.colGutter">
              <el-col :span="layout.colSpan">
                <el-form-item label="目的地" prop="destinationCode" :rules="[{required: true, message: '请选择'}]">
                  <ad-city-select v-model="form.destinationCode" @select="selectCity"/>
                </el-form-item>
              </el-col>
              <el-col :span="layout.colSpan">
                <el-form-item label="送车方式" prop="takeType" :rules="[{required: true, message: '请选择'}]">
                  <ad-status-select v-model="form.takeType" :dict="dict.takecar_type" @select="selectTakeType"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="layout.colGutter">
              <template v-if="form.takeType && (form.takeType == 1 || form.takeType == 2 || form.takeType == 4) ">
                <el-col :span="layout.colSpan" v-if="takeAreaData.length > 0">
                  <el-form-item label="送车地址" prop="takeAreaCode" :rules="[{required: true, message: '请选择'}]">
                    <ad-select placeholder="区" v-model="form.takeAreaCode" :options="takeAreaData"
                               :config="{optionKey: 'name', optionValue: 'code'}"/>
                  </el-form-item>
                </el-col>
                <el-col :span="layout.colSpan" :class="{pull: takeAreaData.length > 0}"
                        :style="takeAreaData.length > 0 ? 'padding-left: 0' : ''">
                  <el-form-item :label="takeAreaData.length == 0 ? '送车地址' : ''" prop="takeAddress"
                                :rules="[{required: true, message: '请输入'}]">
                    <el-input v-model="form.takeAddress" placeholder="请输入详细地址"/>
                  </el-form-item>
                </el-col>
              </template>
            </el-row>
          </div>
        </div>
        <div class="block">
          <div class="title-bar">
            <div class="title"><h2>车辆信息</h2><i class="required"></i></div>
            <div class="op">
              <div class="item">
                <div class="label">车辆数量：</div>
                <el-input-number v-model="form.carNum" :disabled="$route.query.mode == 'edit'" @change="changeCarNum"
                                 :min="1" :max="100" size="mini" style="width: 100px" class="car-num"></el-input-number>
              </div>
            </div>
          </div>
          <div class="content">
            <el-row v-for="(car, index) in form.orderSubList" :key="index" :gutter="layout.colGutter">
              <el-col :span="layout.colSpan">
                <el-form-item label="车辆名称" :prop="`orderSubList[${index}].carName`"
                              :rules="[{required: true, message: '请输入'}]">
                  <el-input v-model="car.carName" placeholder="请输入"/>
                </el-form-item>
              </el-col>
              <el-col :span="layout.colSpan">
                <el-form-item label="车架/车牌号" :prop="`orderSubList[${index}].vin`">
                  <el-input v-model="car.vin" placeholder="请输入" :maxlength="17"/>
                </el-form-item>
              </el-col>
              <el-col :span="5">
                <el-form-item label="保险费" :prop="`orderSubList[${index}].insuranceFee`" class="left-label">
                  <!--                  <ad-input-number v-model="car.insuranceFee" append="元" :precision="2"/>-->
                  <ad-can-input-number :model="car" :prop="['hasInsurance','insuranceFee']" append="元" :precision="2"
                                       :max="99999" placeholder="" disabled/>
                </el-form-item>
              </el-col>
              <el-col :span="layout.colSpan" v-if="car.hasInsurance">
                <el-form-item label="车价值" :prop="`orderSubList[${index}].carCost`">
                  <ad-input-number v-model="car.carCost" append="万元" :precision="2" :max="99999"/>
                </el-form-item>
              </el-col>
              <el-col :span="1" class="row-close">
                <el-button v-if="index > 0 || form.orderSubList.length > 1" size="mini" circle type="primary" plain
                           icon="el-icon-close" @click="delCar(index)"/>
              </el-col>
            </el-row>
          </div>
        </div>
        <div class="block">
          <div class="title-bar">
            <div class="title"><h2>运费信息</h2><i></i></div>
          </div>
          <div class="total-bar">
            <span class="label">应收运费合计：<i>{{`${totalPrice}`}}</i>元</span><span class="tip">　|　说明：应收运费合计 = 应收运费 × 台数 + 客户返款 + 税额 + 保险费 + 提车费 + 送车费</span>
          </div>
          <div class="line" style="margin: 0 24px"></div>
          <div class="content">
            <el-row :gutter="layout.colGutter">
              <el-col :span="layout.colSpan">
                <el-form-item label="运输费" prop="transportFee" :rules="[{required: true, message: '请输入'}]">
                  <ad-input-number v-model="form.transportFee" append="元/每台" :precision="2" :max="99999"/>
                </el-form-item>
              </el-col>
              <el-col :span="layout.colSpan">
                <el-form-item label="客户返款" prop="kickbackFee">
                  <ad-input-number v-model="form.kickbackFee" append="元/共计" :precision="2" :max="99999"/>
                </el-form-item>
              </el-col>
              <el-col :span="layout.colSpan">
                <el-form-item label="开票税额" prop="invoiceFee">
                  <ad-input-number v-model="form.invoiceFee" append="元/共计" :precision="2" :max="99999"/>
                </el-form-item>
              </el-col>
              <!--              <el-col :span="layout.colSpan">-->
              <!--                <el-form-item label="保险费用">-->
              <!--                  <el-input placeholder="请输入"><template slot="append">元/共计</template></el-input>-->
              <!--                </el-form-item>-->
              <!--              </el-col>-->
              <el-col :span="layout.colSpan" v-if="form.pickType == 1 || form.pickType == 2">
                <el-form-item label="提车费用" prop="pickFee" :rules="[{required: true, message: '请输入'}]">
                  <ad-input-number v-model="form.pickFee" append="元" :precision="2" :max="99999"/>
                </el-form-item>
              </el-col>
              <el-col :span="layout.colSpan" v-if="form.takeType == 1 || form.takeType == 2">
                <el-form-item label="送车费用" prop="takeFee" :rules="[{required: true, message: '请输入'}]">
                  <ad-input-number v-model="form.takeFee" append="元" :precision="2" :max="99999"/>
                </el-form-item>
              </el-col>
              <el-col :span="layout.colSpan">
                <el-form-item label="付款方式" prop="paymentType" :rules="[{required: true, message: '请选择'}]">
                  <ad-status-select v-model="form.paymentType" multiple collapse-tags
                                    :dict="form.canSlotPay ? dict.payment_type : (dict.payment_type? dict.payment_type.filter(type => type.value != 4) : [])"
                                    @select="selectPaymentType"/>
                </el-form-item>
              </el-col>
              <el-col :span="layout.colSpan" v-if="form.paymentType && form.paymentType.filter(type => type == 1).length > 0">
                <el-form-item label="现付金额" prop="spotPayFee" :rules="{required: true, message: '请输入'}">
                  <ad-input-number v-model="form.spotPayFee" append="元/共计" :precision="2" :max="99999" />
                </el-form-item>
              </el-col>
              <el-col :span="layout.colSpan" v-if="form.paymentType && form.paymentType.filter(type => type == 2).length > 0">
                <el-form-item label="到付金额" prop="deliveryPayFee" :rules="[{required: true, message: '请输入'}]">
                  <ad-input-number v-model="form.deliveryPayFee" append="元/共计" :precision="2" :max="99999"/>
                </el-form-item>
              </el-col>
              <el-col :span="layout.colSpan" v-if="form.paymentType && form.paymentType.filter(type => type == 3).length > 0">
                <el-form-item label="欠付金额" prop="backPayFee" :rules="[{required: true, message: '请输入'}]">
                  <ad-input-number v-model="form.backPayFee" append="元/共计" :precision="2" :max="99999"/>
                </el-form-item>
              </el-col>
              <el-col :span="layout.colSpan" v-if="form.paymentType && form.paymentType.filter(type => type == 4).length > 0">
                <el-form-item label="月结金额" prop="slotPayFee" :rules="[{required: true, message: '请输入'}]">
                  <ad-input-number v-model="form.slotPayFee" append="元/共计" :precision="2" :max="99999"/>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </div>
        <div class="block">
          <div class="title-bar">
            <div class="title"><h2>其他信息</h2><i></i></div>
          </div>
          <div class="content">
            <el-row :gutter="layout.colGutter">
              <el-col :span="layout.colSpan">
                <el-form-item label="是否加急" prop="hasUrgent">
                  <ad-status-select v-model="form.hasUrgent" :dict="dict.yes_or_no"/>
                </el-form-item>
              </el-col>
              <el-col :span="layout.colSpan">
                <el-form-item label="预约提车时间" prop="appointPickTime">
                  <el-date-picker  style="width: 170px" v-model="form.appointPickTime" value-format="timestamp" format="yyyy-MM-dd HH:mm"
                                  type="datetime" placeholder="请输入" clearable/>
                </el-form-item>
              </el-col>
              <el-col :span="layout.colSpan">
                <el-form-item label="运输方式" prop="transportType">
                  <ad-status-select-no v-model="form.transportType" :dict="dict.transport_way"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="订单备注" prop="remark">
              <el-input v-model="form.remark" placeholder="请输入"/>
            </el-form-item>
          </div>
        </div>
      </el-form>
    </div>
    <div class="op fix-bottom">
      <div class="center">
        <el-button type="primary" plain @click="resetForm">重 置</el-button>
        <el-button type="primary" :loading="saving" @click="save({redirect: '/order/all'})">保 存</el-button>
      </div>
    </div>

    <el-dialog title="添加客户" :visible.sync="settlementAdder.visible" custom-class="ad-dialog" width="500px">
      <settlement-adder :mode="settlementAdder.mode" id="" :data="settlementAdder.data" :visible.sync="settlementAdder.visible" @saved="selectLink"/>
    </el-dialog>
  </div>
</template>

<script>
  import {mapGetters} from 'vuex'
  import bus from '@/utils/bus'
  import AdSuggestion from '@/components/AdSuggestion'
  import AdInputNumber from '@/components/AdInputNumber'
  import AdCanInputNumber from '@/components/AdCanInputNumber'
  import AdSelect from '@/components/AdSelect'
  import AdCitySelect from '@/components/AdCitySelect'
  import AdStatusSelect from '@/components/AdStatusSelect'
  import AdStatusSelectNo from '@/components/AdStatusSelect/noClear'
  import settlementAdder from '@/views/dialog/settlementAdder'
  import {getQueryVar} from '@/utils/url'
  import adPageForm from '@/mixins/adPageForm'
  import {
    getCompanyList as getSuggestCompanyList,
    getCompanyLineList as getSuggestCompanyLineList,
    getBargainList as getSuggestBargainList,
    getLinePrice,
  } from '@/api/suggestion'
  import {get as getAreaData} from '@/api/city/area'
  import {add, edit, getEditDetail as get} from '@/api/order/all'
  import {getDetail as getCompleteDetail} from '@/api/order/complete'
  import { dataFilter } from 'echarts/lib/component/marker/markerHelper'

  class FormCar {
    carName = undefined  // 车辆名称
    vin = undefined  // 车架/车牌号
    carCost = undefined  // 车价值
    hasInsurance = 0          // 是否有保险费
    insuranceFee = undefined  // 保险费
  }

  class Form {
    origin = 2
    //type = undefined  // 客户类型
    companyId = undefined
    companyName = undefined  // 公司名称
    linkmanName = undefined  // 委托联系人
    linkmanPhone = undefined  // 委托联系电话
    customerLineId = undefined  // 线路信息

    startCode = undefined  // 出发地
    destinationCode = undefined  // 目的地
    pickType = undefined  // 提车方式
    pickLinkmanName = undefined  // 提车联系人
    pickLinkmanPhone = undefined  // 提车联系电话
    pickAreaCode = undefined  // 提车区
    pickAddress = undefined  // 提车地址
    takeType = undefined  // 送车方式
    consigneeName = undefined  // 收货联系人
    consigneePhone = undefined  // 收货联系电话
    takeAreaCode = undefined  // 送车区
    takeAddress = undefined  // 送车地址

    carNum = 1 // 车辆数量
    orderSubList = [new FormCar()]

    transportFee = undefined  // 运输费
    kickbackFee = undefined  // 客户返款
    invoiceFee = undefined  // 开票税额
    pickFee = undefined  // 提车费
    takeFee = undefined  // 送车费
    paymentType = []         // 付款方式
    spotPayFee = undefined  // 现付
    deliveryPayFee = undefined  // 到付
    backPayFee = undefined  // 欠付
    slotPayFee = undefined  // 月结
    canSlotPay = false      // 是否可月结

    hasUrgent = 0          // 是否加急
    transportType = 1      //
    appointPickTime = undefined  // 预约提车时间
    remark = undefined  // 备注
  }

  export default {
    name: 'order-add',
    components: {
      AdSuggestion,
      AdInputNumber,
      AdCanInputNumber,
      AdSelect,
      AdCitySelect,
      AdStatusSelect,
      AdStatusSelectNo,
      settlementAdder
    },
    mixins: [adPageForm({add, edit, get})],
    dicts: ['pickcar_type', 'takecar_type', 'payment_type', 'yes_or_no','transport_way','premium_allocation'],
    data() {
      return {
        options:[],
        showCompany:true,
        layout: {colGutter: 28, colSpan: 6, rowGutter: 16},
        pickAreaData: [],
        takeAreaData: [],
        suggestedCustomerLineList: [],
        form: new Form(),
        settlementAdder: {
          visible: false,
          mode: ''
        }
      }
    },
    computed: {
      ...mapGetters(['cachedPages']),
      // 运费合计 = 运输费 * 车辆数量 + 保险费 * 车辆数量 + 客户返款 + 开票税额 + 提车费用 + 送车费用
      totalPrice: {
        get() {
          if(this.dict.premium_allocation.length > 0){
            // 拿到this.dict.premium_allocation每一项value等于"limit_money"去拿他的label
            let limit_money = this.dict.premium_allocation.find(item => item.value === 'limit_money').label
            // 拿到this.dict.premium_allocation每一项value等于"limit_pay"去拿他的label
            let limit_pay = this.dict.premium_allocation.find(item => item.value === 'limit_pay').label
            // 拿到this.dict.premium_allocation每一项value等于"pay_percentage"去拿他的label
            let pay_percentage = this.dict.premium_allocation.find(item => item.value === 'pay_percentage').label
            let insuranceFee = 0
            // let kickbackFee = 0
            this.form.orderSubList.forEach(car => {
              // 有保险时根据车价值计算保险费
              if (car.hasInsurance) {
                // 10万以内按30元算，10万以上万三
                if (car.carCost * 10000 < Number(limit_money)) {
                  car.insuranceFee = Number(limit_pay)
                } else {
                  let price = car.carCost * 10000 * Number(pay_percentage) / 10000
                  car.insuranceFee = Math.floor(price / 10) * 10 // 去除个位数
                }
                // 无保险时清空车价值
              } else {
                car.carCost = undefined
              }
              insuranceFee += Number(car.insuranceFee || 0)
              // kickbackFee += Number(car.kickbackFee || 0)
            })
            const totalPrice =
              Number(this.form.transportFee || 0) * this.form.orderSubList.length + insuranceFee + // * Number(this.form.carNum || 0) +
              Number(this.form.kickbackFee || 0) + Number(this.form.invoiceFee || 0) + // - Number(this.form.discountFee || 0) +
              Number(this.form.pickFee || 0) + Number(this.form.takeFee || 0) // + insuranceFee + kickbackFee
            this.form.totalFee = totalPrice
            return totalPrice
          }
        },
        set() {
        }
      }
    },
    created() {
      if (this.$route.query.mode == 'complete') {
        getCompleteDetail(this.$route.query.ids).then(res => {
          this.form = res.data
        })
      }
    },
    watch: {
      form: {
        immediate: true,
        deep: true,
        handler(form) {
          this.autoCompleteForOnlyOnePaymentType()
        }
      },
      'form.startCode': {
        immediate: true,
        handler(code) {
          this.setPickArea()
        }
      },
      'form.destinationCode': {
        immediate: true,
        handler(code) {
          this.setTakeArea()
        }
      }
    },
    methods: {
      dataFilter,
      getSuggestCompanyList,
      getSuggestBargainList,
      async resetForm() {
        if (this.$route.query.mode == 'edit') {
          this.form = (await this.getDetail()).data
        } else if (this.$route.query.mode == 'complete') {
          this.form = (await getCompleteDetail(this.$route.query.ids)).data
        } else {
          this.$refs.form.resetFields()
          this.form.carNum = 1
          this.form.orderSubList = [new FormCar()]
          this.form.paymentType = []
          this.selectPaymentType()
        }
      },
      beforeSave() {
        const acc = Number(this.form.spotPayFee || 0) + Number(this.form.deliveryPayFee || 0) + Number(this.form.backPayFee || 0) + Number(this.form.slotPayFee || 0)
        console.log(acc != this.totalPrice)
        if (acc != this.totalPrice) {
          this.$notify({
            title: '付款方式与合计费用不符合业务要求，请核实后重新输入',
            duration: 5000,
            type: 'error'
          })
          return false
        } else {
          return true
        }
      },
      selectLink(link) {
        this.setLink(link)
        this.setPick()
      },
      // selectLinkConsignee(link) {
      //   this.form.consigneeName = link.name
      //   this.form.consigneePhone = link.phone
      // },
      removeLink() {
        // 清空的时候显示公司输入框
        this.showCompany = true
        this.form.companyId = ''
        this.form.companyName = ''
        this.form.linkmanId = ''
        this.form.linkmanName = ''
        this.form.consigneeName = ''
        this.form.consigneePhone = ''
        this.options = []
        this.form.linkmanPhone = undefined
        this.form.pickLinkmanName = ''
        this.form.pickLinkmanPhone = undefined
        this.form.canSlotPay = false
        this.suggestedCustomerLineList = []
      },
      // removeConsignee() {
      //   this.form.consigneeName = ''
      //   this.form.consigneePhone = undefined
      // },
      dataFilterConsigneeName(val){
        this.form.consigneeName = val
      },
      dataFilterConsigneePhone(val){
        this.form.consigneePhone = val
      },
      selectNamePhone(link) {
        // 根据link的值去匹配this.options的phone或者name

        let option = this.options.find(item => item.name == link || item.phone == link)

        this.form.consigneeName = option.name
        this.form.consigneePhone = option.phone
      },
      setLink(link) {
        // 如果是个人没有公司名称的情况就隐藏公司输入框
        if(!link.companyName){
          this.showCompany = false
        }else {
          this.showCompany = true
        }
        this.form.companyId = link.companyId
        this.form.companyName = link.companyName
        this.form.linkmanId = link.linkmanId
        this.form.linkmanName = link.linkmanName
        this.form.linkmanPhone = link.linkmanPhone
        this.form.canSlotPay = link.nature
        getSuggestCompanyLineList(this.form.companyId).then(res => this.suggestedCustomerLineList = res.data)
        getSuggestBargainList({linkmanId:link.linkmanId}).then(res => {
          this.options = res.data
          this.form.consigneeName = this.options[0].name
          this.form.consigneePhone = this.options[0].phone
        })
      },
      selectSuggestedCustomerLine(line) {
        this.form.startCode = line.startCode
        this.form.destinationCode = line.destinationCode
        this.form.transportFee = line.transportFee
        this.form.orderSubList.map(car => {
          car.carName = line.carType
          return car
        })
      },
      selectPickType() {
        this.setPick()
        this.setPickArea()
      },
      setPick() {
        if (this.form.pickType && this.form.pickType == 3) {
          this.form.pickLinkmanName = ''
          this.form.pickLinkmanPhone = undefined
          this.form.pickAddress = ''
        } else {
          this.form.pickLinkmanName = this.form.linkmanName
          this.form.pickLinkmanPhone = this.form.linkmanPhone
        }
        // 清空提车费
        if (this.form.pickType && (this.form.pickType == 3 || this.form.pickType == 4)) {
          this.form.pickFee = undefined
        }
      },
      setPickArea() {
        if (this.form.pickType && this.form.pickType == 3) {
          if (this.form.pickAreaCode) this.form.pickAreaCode = ''
          this.pickAreaData = []
        } else if (this.form.pickType && this.form.startCode) {
          // const code = this.form.startCode.slice(0, 4) + '00'
          const code = this.form.startCode
          getAreaData(code).then(res => {
            this.pickAreaData = res.data
          })
        }
      },
      selectTakeType() {
        this.setTake()
        this.setTakeArea()
      },
      setTake() {
        if (this.form.takeType && this.form.takeType == 3) {
          this.form.takeFee = undefined
          this.form.takeAddress = ''
        }
        // 清空送车费
        if (this.form.takeType && (this.form.takeType == 3 || this.form.takeType == 4)) {
          this.form.takeFee = undefined
        }
      },
      setTakeArea() {
        if (this.form.takeType && (this.form.takeType == 3 || this.form.takeType == 4)) {
          if (this.form.takeAreaCode) this.form.takeAreaCode = ''
          this.takeAreaData = []
        } else if (this.form.takeType && this.form.destinationCode) {
          // const code = this.form.destinationCode.slice(0, 4) + '00'
          const code = this.form.destinationCode
          getAreaData(code).then(res => {
            this.takeAreaData = res.data
          })
        }
      },
      selectCity(city) {
        this.form.customerLineId = undefined
        if (this.form.startCode && this.form.destinationCode) {
          getLinePrice({startCode: this.form.startCode, destinationCode: this.form.destinationCode}).then(res => {
            this.form.transportFee = res.data.totalFee
          })
        } else {
          this.form.transportFee = ''
        }
      },
      changeCarNum() {
        // const cars = new Array(this.form.carNum)
        // this.form.orderSubVOList = cars.fill(new FormCar())
        if (this.form.carNum > this.form.orderSubList.length) {
          const count = this.form.carNum - this.form.orderSubList.length
          for (let n = 0; n < count; n++) {
            this.form.orderSubList.push(new FormCar())
          }
        } else if (this.form.carNum < this.form.orderSubList.length) {
          this.form.orderSubList.splice(this.form.carNum, this.form.orderSubList.length - 1)
        }
      },
      delCar(index) {
        this.form.orderSubList.splice(index, 1)
        this.form.carNum = this.form.orderSubList.length
      },
      selectPaymentType() {
        // 清空所有字段
        this.form.spotPayFee = undefined
        this.form.deliveryPayFee = undefined
        this.form.backPayFee = undefined
        this.form.slotPayFee = undefined

        this.autoCompleteForOnlyOnePaymentType()
      },
      autoCompleteForOnlyOnePaymentType() {
        if (this.loading) return
        // 清空未选中字段
        // if (!(this.form.paymentType.includes(1) || this.form.paymentType.includes('1'))) { // 没现付
        //   this.form.spotPayFee = undefined
        // }
        // if (!(this.form.paymentType.includes(2) || this.form.paymentType.includes('2'))) { // 没到付
        //   this.form.deliveryPayFee = undefined
        // }
        // if (!(this.form.paymentType.includes(3) || this.form.paymentType.includes('3'))) { // 没欠付
        //   this.form.backPayFee = undefined
        // }
        // if (!(this.form.paymentType.includes(4) || this.form.paymentType.includes('4'))) { // 没月付
        //   this.form.slotPayFee = undefined
        // }

        // 付款方式只有一项时，直接赋值应收运费合计
        console.log(this.form.spotPayFee, this.form.deliveryPayFee, this.form.backPayFee, this.form.slotPayFee)
        if (this.form.paymentType && this.form.paymentType.length == 1) {
          if (this.form.paymentType.filter(type => type == 1).length > 0) {

           this.$nextTick(() => {
             this.form.spotPayFee = this.totalPrice // 现付
           })
          } else if (this.form.paymentType.filter(type => type == 2).length > 0) {
            this.$nextTick(() => {
              this.form.deliveryPayFee = this.totalPrice // 到付
            })
          } else if (this.form.paymentType.filter(type => type == 3).length > 0) {
            this.$nextTick(() => {
              this.form.backPayFee = this.totalPrice // 欠付
            })
          } else if (this.form.paymentType.filter(type => type == 4).length > 0) {
            this.$nextTick(() => {
              this.form.slotPayFee = this.totalPrice // 月付
            })
          }
        }
      },
      openSettlementAdder(mode) {
        this.settlementAdder.visible = true
        if (!this.form.linkmanId && this.form.linkmanPhone) {
          this.settlementAdder.data = {linkmanPhone: this.form.linkmanPhone}
        }
        if (mode == 'edit') {
          this.settlementAdder.mode = mode
        } else {
          this.settlementAdder.mode = ''
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
  .center {
    width: 1300px;
  }

  .left-label {
    &::v-deep .el-form-item__label-wrap {
      margin-left: 0 !important;
    }
  }

  .row-close {
    padding-top: 4px;
  }

  ::v-deep .car-num .el-input__inner {
    text-align: center;
  }

  .page-form {
    display: flex;
    flex: 1;
    background: #eee;
    flex-direction: column;
    align-items: center;

    h1 {
      margin: 15px 0;
      text-align: center;
      font-size: 24px;
      font-weight: bold;
    }

    // 背景多图 https://www.cnblogs.com/xiaolantian/p/12629076.html
    .form-wrapper {
      margin-top: 24px;
      margin-bottom: 80px;
      background-color: #fff;
      background-image: linear-gradient(to right, #5EB9FF 25%, #DEDEDE 25%, #DEDEDE 50%, #5694B7 50%, #5694B7 75%, #DEDEDE 25%);
      background-size: 80px 2px;
      background-repeat: repeat-x;

      .form {
        margin-bottom: 25px;
        padding: 0 24px;

        .title-bar {
          display: flex;
          height: 40px;
          border-bottom: 1px solid #85AFD6;
          background: #F3F3F3;
          align-items: center;

          .title {
            display: flex;
            margin: 0 auto 0 24px;
            align-items: center;

            h2 {
              font-size: 14px;
              font-weight: bold;
            }

            i {
              font-size: 14px;
              color: #979797;
              font-style: inherit;

              &.required {
                color: red;
              }
            }
          }

          .op {
            margin-right: 24px;

            .item {
              display: flex;
              align-items: center;

              .label {
                font-size: 14px;
                color: #303030;
              }
            }
          }
        }

        .total-bar {
          height: 50px;
          line-height: 50px;
          font-size: 14px;

          .label {
            margin-left: 24px;
            font-size: 16px;
            font-weight: bold;

            i {
              margin-right: 4px;
              font-style: normal;
              color: #EC2D0F;
            }
          }

          .tip {
            margin-left: 6px;
            font-size: 12px;
            color: #888;
          }
        }

        .block {
          padding-bottom: 10px;
          border: 1px solid #DCDCDC;

          & + .block {
            margin-top: 24px;
          }

          .content {
            padding: 24px 24px 0;

            .el-form-item {
              display: flex;
            }
          }
        }
      }
    }
  }
</style>